package com.api.base.config.auth;

import com.api.core.ServiceException;
import com.api.core.config.AuthUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 等级拦截
 */
public class LevelInterceptor extends OncePerRequestFilter {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    //未认证前能访问的接口
    List<String> na  = Arrays.asList("/identification/save","/user/info/update","/game/profile/user","/game/profile/delete","/game/profile/save","/user/transaction/password/update","/game/list","/user/info/detail","/coupon/list/user","/advertisement/list/user","/manage/info/detail","/manage/info/update","/countries/states","/countries/all","/recharge/order/payment/callback");

    //基础会员嫩访问的接口
    List<String> base  = Arrays.asList("/tournament/detail","/tournament/list","/tournament/signup");


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 如果是OPTIONS则结束请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return;
        }
        if(request.getMethod().toUpperCase().equals("OPTIONS")){
            return;//通过所有OPTION请求
        }
        String authHeader = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authHeader)) {
            authHeader = request.getHeader(JwtAuthenticationTokenFilter.WS_TOKEN_HEADER);
        }

        /**
         * 带token访问的鉴权
         */
        logger.info("请求路径"+request.getRequestURI());
           if (authHeader != null) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            AuthUser authUser = (AuthUser) authentication.getPrincipal();
            if(authUser.getLevel().equals("NA") && (authUser.getType() == 2 || authUser.getType() == 3) && !na.contains(request.getRequestURI())){
                throw new  ServiceException("Please filled in all personal profile before you can kickstart your account! Enjoy!");
            }

        }
        filterChain.doFilter(request, response);
    }
}
